package com.example.ezexcel.util;

public class KMPStringMatching {
    // KMP算法的部分匹配表计算
    public static int[] computeKMPTable(String pattern) {
        int[] lps = new int[pattern.length()];
        int len = 0;
        int i = 1;
        lps[0] = 0;

        while (i < pattern.length()) {
            if (pattern.charAt(i) == pattern.charAt(len)) {
                len++;
                lps[i] = len;
                i++;
            } else {
                if (len != 0) {
                    len = lps[len - 1];
                } else {
                    lps[i] = len;
                    i++;
                }
            }
        }
        return lps;
    }

    // KMP算法主体
    public static boolean KMPSearch(String txt, String pat, int[] lps) {
        int M = pat.length();
        int N = txt.length();
        int i = 0; // index for txt[]
        int j = 0; // index for pat[]

        while (i < N) {
            if (pat.charAt(j) == txt.charAt(i)) {
                j++;
                i++;
            }
            if (j == M) {
                return true; // found pattern at index i - j
            } else if (i < N && pat.charAt(j) != txt.charAt(i)) {
                if (j != 0) {
                    j = lps[j - 1];
                } else {
                    i = i + 1;
                }
            }
        }
        return false; // pattern not found
    }
}
